<?php

/* 公用方法放置地 */
class service_globals extends gdl_components_baseservice
{

	/* 所有错误提示信息 */
	public $error ='';
	public $typesf;
	public $types;

	
	public function __construct(){

		$this->types = ['single'=>'1','more'=>'2','judge'=>'3','gapFilling'=>'4','subjectivity'=>'5'];
		$this->typesf = ['1'=>'single','2'=>'more','3'=>'judge','4'=>'gapFilling','5'=>'subjectivity'];
		
	}

	public function secsToStrws($secs) {
		$r = '';

        if ($secs >= 86400) {
            $days = floor($secs / 86400);
            $secs = $secs % 86400;
            $r = $days . ' 天';
            if ($days <> 1) {
                $r .= '';
            }
            if ($secs > 0) {
                $r .= ' ';
            }
        }
        if ($secs >= 3600) {
            $hours = floor($secs / 3600);
            $secs = $secs % 3600;
            $r .= $hours . '时';
            if ($hours <> 1) {
                $r .= '';
            }
            if ($secs > 0) {
                $r .= ' ';
            }
        }
        if ($secs >= 60) {
            $minutes = floor($secs / 60);
            $secs = $secs % 60;
            $r .= $minutes . '分';
            if ($minutes <> 1) {
                $r .= '';
            }
            if ($secs > 0) {
                $r .= '';
            }
        }

        if ($secs > 0) {
            $r .= $secs.'秒';
        }
        return $r;

    }
	
	
	public function secsToStrwsdian($secs) {

        if ($secs >= 86400) {
            $days = floor($secs / 86400);
            $secs = $secs % 86400;
            $r = $days . ' ：';
            if ($days <> 1) {
                $r .= '';
            }
            if ($secs > 0) {
                $r .= ' ';
            }
        }
        if ($secs >= 3600) {
            $hours = floor($secs / 3600);
            $secs = $secs % 3600;
            $r .= $hours . '：';
            if ($hours <> 1) {
                $r .= '';
            }
            if ($secs > 0) {
                $r .= ' ';
            }
        }
        if ($secs >= 60) {
			
            $minutes = floor($secs / 60);
            $secs = $secs % 60;
            $r .= $minutes . '：';
            if ($minutes <> 1) {
                $r .= '';
            }
            if ($secs > 0) {
                $r .= '';
            }
        }
        $r .= $secs;
        if ($secs <> 1) {
            $r .= '';
        }
		/*
		if($secs<10){
			$r = '00：0'.$secs;
		} else if($secs>10 && $secs<60){
			$r = '00：'.$secs;
		}*/
        return $r;
    }
	
	public function secsToStr($secs) {
        if ($secs >= 86400) {
            $days = floor($secs / 86400);
            $secs = $secs % 86400;
            $r = $days . 'Y';
            if ($days <> 1) {
                $r .= '';
            }
            if ($secs > 0) {
                $r .= ' ';
            }
        }
        if ($secs >= 3600) {
            $hours = floor($secs / 3600);
            $secs = $secs % 3600;
            $r .= $hours . 'h';
            if ($hours <> 1) {
                $r .= '';
            }
            if ($secs > 0) {
                $r .= ' ';
            }
        }
        if ($secs >= 60) {
            $minutes = floor($secs / 60);
            $secs = $secs % 60;
            $r .= $minutes . "'";
            if ($minutes <> 1) {
                $r .= '';
            }
            if ($secs > 0) {
                $r .= '';
            }
        }
        $r .= $secs;
        if ($secs <> 1) {
            $r .= "''";
        }
        return $r;
    }
	
	public function dwSorc($dw_sorc){
		$scores = [0=>[],1=>[]];
		foreach($dw_sorc as $vs) {
             $scores[0][$vs['0']][$vs['2']] = [$vs['3'], $vs['4']];
			 $scores[1][$vs['0']] = [$vs['3'], $vs['4']];
        }
		return $scores;
	}
	
	//计算提数和得分
	public function scores($question,$userAnswer,$dw_sorc){
		$dwSorc = self::dwSorc($dw_sorc);
		$scores= $dwSorc[0];
		$scores2 = $dwSorc[1];
		
		
		$answer = [];
		foreach($userAnswer as $ku=>$vu){
			if(empty($ku)){
				
				foreach($vu as $kan=>$van){
					if(!empty($van)){
					$answer[$van['id']] = ['answer'=>$van['answer'],'id'=>$van['id']];
					}
				}
			} else {
				$answer[$vu['id']] = ['answer'=>$vu['answer'],'id'=>$vu['id']];
			}
		}
		//$answer = $userAnswer;

		$pass = 0;
		$nopass = 0;
		$qscore = [];
		foreach ($question as $key => $tmp) {
				$key = empty($this->types[$key]) ? 0 : $this->types[$key];

				$qscore[$key]=['num'=> count($tmp),'score'=>0,'pass'=>0];
				if($key>3){ 
					$qscore[$key]['score'] = 901;
					$qscore[$key]['pass']=901;
					continue;
				}
				foreach($tmp as $k=>$v){
                    if(!empty($answer[$v['id']])){
                  
                            if($answer[$v['id']]['answer'] == $v['answer']){
								if(empty($scores[$key][$v['sectionId']])){
									$qscore[$key]['score'] += $scores2[$key][1];
								} else {
									$qscore[$key]['score'] += $scores[$key][$v['sectionId']][1];
								}
                                $qscore[$key]['pass']++;
                            }
                        
                    }
				}
                
        }
		return $qscore;
	}
	//修改备选答案格式
	public function selectarr($answer){
		if(empty($answer) || !is_array($answer)) return $answer;
		$list = [];
		foreach($answer as $k=>$v){
			
			preg_match_all('/src="(.*)"/iUs', $v, $out);
			$img=empty($out[1][0]) ? '' : $out[1][0];

			$list[] = ['img'=>$img,'name'=>$k.'.'.preg_replace("/<img.+?\/>/", "", $v)];
		}
		return $list;
	}
	
	public function answSort($str=''){
		if($str=='') return '';
		if(preg_match("/^[a-zA-Z\s]+$/",$str)){
			$arr=str_split($str);//提取出字符，放入数组
			usort($arr,'strcmp');//对字符数组进行排序
			$str=implode('',$arr);//形成排序后的字符串
		}
		return $str;
		
	}
	
	
	//过滤XSS攻击
	public function reMoveXss($val) {
		$val = preg_replace('/([\x00-\x08])/', '', $val);
		$val = preg_replace('/([\x0b-\x0c])/', '', $val);
		$val = preg_replace('/([\x0e-\x19])/', '', $val);
		$search = 'abcdefghijklmnopqrstuvwxyz';
		$search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$search .= '1234567890!@#$%^&*()';
		$search .= '~`";:?+/={}[]-_|\'\\';
		for ($i = 0; $i < strlen($search); $i++) {
			$val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val);
			$val = preg_replace('/(&#0{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val);
		}

		$ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'base');
		$ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
		$ra = array_merge($ra1, $ra2);
		$found = true;
		while ($found == true) {
			$val_before = $val;
			for ($i = 0; $i < sizeof($ra); $i++) {
				$pattern = '/';
				for ($j = 0; $j < strlen($ra[$i]); $j++) {
					if ($j > 0) {
						$pattern .= '(';
						$pattern .= '(&#[xX]0{0,8}([9ab]);)';
						$pattern .= '|';
						$pattern .= '|(&#0{0,8}([9|10|13]);)';
						$pattern .= ')*';
					}
					$pattern .= $ra[$i][$j];
				}
				$pattern .= '/i';
				$replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag
				$val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
				if ($val_before == $val) {
					$found = false;
				}
			}
		}
		return $val;
	}

/**
 * 安全过滤数据
 * @param string	$str		需要处理的字符或数组
 * @param string	$type		返回的字符类型，支持，string,int,float,html
 * @param mixed		$default	当出现错误或无数据时默认返回值
 * @return 		mixed		当出现错误或无数据时默认返回值
 */
	public function getStr($str, $type = 'string', $default = '') {
		//如果为空则为默认值
		if ($str === '')
			return $default;
		if (is_array($str)) {
			$_str = array();
			foreach ($str as $key => $val) {
				$_str[$key] = getStr($val, $type, $default);
			}
			return $_str;
		}
		//转义
		if (!get_magic_quotes_gpc())
			$str = addslashes($str);
		switch ($type) {
			case 'string': //字符处理
				$_str = strip_tags($str);
				$_str = str_replace("&rdquo;", '”', $_str);
				$_str = str_replace("&ldquo;", '“', $_str);
				$_str = str_replace("'", '&#39;', $_str);
				$_str = str_replace("\"", '&quot;', $_str);
				$_str = str_replace("\\", '', $_str);
				$_str = str_replace("\/", '', $_str);
				$_str = str_replace("+/v", '', $_str);
				$_str = urldecode($_str);
				$_str = str_ireplace(array('!','@','#','$','^','&',' ','\r','\n','\r\n'), '', $_str);
				break;
			case 'int': //获取整形数据
				$_str = intval($str);
				break;
			case 'float': //获浮点形数据
				$_str = floatval($str);
				break;
			case 'html': //获取HTML，防止XSS攻击
				$_str = self::reMoveXss($str);
				break;
			default: //默认当做字符处理
				$_str = strip_tags($str);
		}

			return $_str;
		}
		
		
		/**
		 * 生成随机字符串
		 * @param string $prefix
		 * @return string
		 */
		function get_random($prefix = '') {
			return $prefix . base_convert(time() * 1000, 10, 36) . "_" . base_convert(microtime(), 10, 36) . uniqid();
		}

        /**
         * 节点遍历
         *
         * @param        $list
         * @param string $pk
         * @param string $pid
         * @param string $child
         * @param int    $root
         *
         * @return array
         */
        function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0) {
            // 创建Tree
            $tree = [];
            if (is_array($list)) {
                // 创建基于主键的数组引用
                $refer = [];
                foreach ($list as $key => $data) {
                    if ($data instanceof \think\Model) {
                        $list[$key] = $data->toArray();
                    }
                    $refer[$data[$pk]] = & $list[$key];
                }
                foreach ($list as $key => $data) {
                    // 判断是否存在parent
                    if (!isset($list[$key][$child])) {
                        $list[$key][$child] = [];
                    }
                    $parentId = $data[$pid];
                    if ($root == $parentId) {
                        $tree[] = & $list[$key];
                    } else {
                        if (isset($refer[$parentId])) {
                            $parent = & $refer[$parentId];
                            $parent[$child][] = & $list[$key];
                        }
                    }
                }
            }

            return $tree;
        }

    /**
     * @todo 将对象转换成数组
     * @param unknown_type $obj
     * @return unknown
     */
    function object_to_array($obj){
        $ret = array();
        foreach($obj as $key =>$value){
            if(gettype($value) == 'array' || gettype($value) == 'object'){
                $ret[$key] = $this->object_to_array($value);
            }
            else{
                $ret[$key] = $value;
            }
        }
        return $ret;
    }

    function format_html($str){
        $str = str_replace('&ldquo;','"',$str);
        $str = str_replace('&quot;','"',$str);
        $str = str_replace('&rdquo;', '"',$str);
        $str = str_replace('&middot;', '·',$str);
        $str = str_replace('&lsquo;', '‘',$str);
        $str = str_replace('&rsquo;', '’',$str);
        $str = str_replace('&hellip;', '…', $str);
        $str = str_replace('&mdash;', '—', $str);
        return $str;
    }

    /**
     * 把二维数组的id转换成键值
     * @param $arr
     * @return array|bool
     *
     */
    function setArrKeyId($arr) {
        if (!isset($arr))
            return false;
        $arrs = [];
        foreach ($arr as $key => $value) {
            $arrs[$value['id']] = $value;
        }
        return $arrs;
    }
    /**
     * 获取日期是否是休息日
     * @param $date @@选择日期 2018-07-11
     * @param $workdayKey @@工作日定义
     * @param $holidayKey @@工作日定义
     * @param $specialWorkdayKey @@特殊工作日定义
     * @return bool false是节假日  true工作日
     */
    function getDateIsHolidaysAndFestivals($date,$workdayKey,$holidayKey,$specialWorkdayKey){
        //判断用户在选择的日期是否需要打卡
        $undate = strtotime($date);//选择日期的时间戳
        //判断日期是否属于休息日
        $wDate = date('w',$undate);
        if ($wDate==0){
            $wDate=7;
        }
        if (in_array($wDate,$workdayKey)){//选择的日期为工作日 正常情况下需要打卡
            //判断当天是否为节假日
            if (in_array($wDate,$holidayKey)){//是节假日不需要打卡
                //判断当前日期 是否属于特殊工作日
                if (in_array($wDate,$specialWorkdayKey)){//选择日期为特殊工作日 不是特殊工作日才允许不打卡
                    return true;
                }else{
                    return false;//是节假日中 不需要打卡
                }
            }else{
                return true;
            }
        }else{//休息日 本身不需要打卡 但是有特殊工作日时需求打卡
            //判断当前日期 是否属于特殊工作日
            if (in_array($wDate,$specialWorkdayKey)){//选择日期为特殊工作日
                return true;
            }elseif (in_array($wDate,$holidayKey)) {//是节假日不需要打卡
                return false;
//                        $result->message = "节假日,不需要打卡！";
            } else{
                return false;
//                        $result->message = "休息日,不需要打卡！";
            }
        }
    }
}	
